今天要來談的是,如何在 Composition API 中定義方法~
首先,如同上一篇提過的 : 在 composition API 是沒有 this 的。
在 options API 中我們會用 this. 去取得 data 的資料,但在 Composition API 中我們現在是用 ref / reactive 來定義資料。
<div id="app">
    {{num}}
    <button type="button" @click="add(5)">累加</button>
    <button type="button" @click="getCount">取得累加次數</button>
</div>
const app = Vue.createApp({
    setup(){
        const num = ref(1);
        
        // 定義方法
        // function add(n){
        //     num.value += n;
        // }
        // 箭頭函式的寫法
        const add = (n)=>{
            num.value += n;
        }
        
        return{
            num,
            add
        }
    }
})
app.mount('#app')
像 countAdd 這樣不須匯出畫面的值,我們就不必用 ref / reactive 來定義他。如此一來,這個值就會被封裝在setup 裡面,我們不必去定義額外的ref,而這些值也不會洩露出來。
const app = createApp({
    setup(){
        const num = ref(1)
        let countAdd = 0; // 累加次數,不需要匯出的值(如 : 系統參數、api路徑)
    
        const add = (n)=>{
            num.value += n;
            countAdd++
        }
        const getCount = ()=>{
            console.log(countAdd)
        }
        
        return{
            num,
            add,
            getCount
        }
    }
})
app.mount(#app)